<!--
 * @Description: 
 * @Date: 2024-07-08 09:20:03
 * @LastEditTime: 2024-07-26 11:27:28
-->
<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="80px">
      <el-row>
        <el-col :span="24">
          <el-form-item label="相册名称" prop="name">
            <el-input v-model="formData.name" placeholder="请输入相册名称" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="可见范围" prop="remark">
            <el-radio-group v-model="formData.remark" @change="handleChange">
              <el-radio :label="1">全体人员</el-radio>
              <el-radio :label="2">指定对象</el-radio>
              <el-radio :label="3">仅自己可见</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>

    <TreeTransfer
      v-if="treeVisible"
      ref="treeTransferRef"
      node-key="id"
      :fromData="treeData"
      :toData="toData"
      :defaultProps="transferProps"
      @change="treeChange"
      :title="['选择人员', '已选择人员']"
    />
  </Dialog>
</template>

<script setup lang="ts">
import TreeTransfer from './treeTransfer.vue'
import { FormRules } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import * as albumphoto from '@/api/countryside/albumphoto/index'
import { cloneDeep } from 'lodash-es'

const userStore = useUserStore()
const message = useMessage()
const { t } = useI18n()
let treeTransferRef = ref() // 树形穿梭框
let treeVisible = ref(false)
let treeData = ref([]) // 树形数据
let toData = ref([]) // 选中的ids数据
let changeName = ref()
const transferProps = ref({
  label: 'label',
  children: 'children',
  disabled: 'disabled'
})
const emit = defineEmits(['success'])
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('新增相册') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formData = reactive({
  id: '',
  name: '',
  remark: undefined,
  userIds: []
})
const formRules = reactive<FormRules>({
  name: [{ required: true, message: '相册名称不能为空', trigger: 'blur' }],
  remark: [{ required: true, message: '可见范围不能为空', trigger: 'change' }]
})
const formRef = ref()
/**
 * @description:打开弹窗
 * @param {*} title 标题
 * @param {*} id id
 * @return {*}
 */
const open = async (title, id) => {
  dialogTitle.value = title
  resetForm()
  dialogVisible.value = true

  if (id) {
    formLoading.value = true
    formData.id = id
    try {
      const data = await albumphoto.getAlbum(id)
      Object.assign(formData, data)
      formData.remark = Number(formData.remark)
      changeName.value = formData.name
      handleChange(formData.remark)

      formData.remark == 2 ? (treeVisible.value = true) : (treeVisible.value = false)
    } finally {
      formLoading.value = false
    }
  }
  getTreeData()
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗
watch
/**
 * @description: 树形窜梭框改变回调
 * @param {*} value
 * @return {*}
 */
const treeChange = (value) => {
  console.log(value)
}
/**
 * @description: 表单提交
 * @return {*}
 */
const submitForm = async () => {
  if (!formRef) return
  const valid = await formRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    if (formData.remark == 2) {
      treeTransferRef.value.showChange()
      let childs = treeTransferRef.value.childIds.map((item) => {
        return Number(item.split('-')[1])
      })
      if (childs.length <= 0) return message.error('请选择人员')
      formData.userIds = Array.from(new Set(childs))
    } else if (formData.remark == 1) {
      formData['userIds'] = []
    } else if (formData.remark == 3) {
      formData['userIds'] = [userStore.user.id]
    }
    if (dialogTitle.value == '新增相册') {
      await albumphoto.createAlbum({
        ...toRaw(formData),
        id: undefined
      })
      message.success(t('common.createSuccess'))
    } else {
      console.log(changeName.value)
      console.log(formData.name)
      await albumphoto.updateAlbum({
        ...toRaw({
          ...formData,
          createTime: undefined,
          name: changeName.value == formData.name ? undefined : formData.name
        })
      })
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    //发送操作成功的事件
    emit('success', true)
  } finally {
    formLoading.value = false
  }
}
/**
 * @description: 范围切换
 * @param {*} value
 * @return {*}
 */
const handleChange = async (value) => {
  if (value == 2) {
    treeVisible.value = true
    if (toData.value.length > 0) {
      setTimeout(() => {
        treeTransferRef.value.checkedRight = true
        treeTransferRef.value.rightAllCheck()
      }, 0)
    }
  } else {
    treeVisible.value = false
  }
}
const getTreeData = async () => {
  let data = await albumphoto.getUserThree({ ids: [3, 4] })
  if (dialogTitle.value == '新增相册' || formData.remark != 2) {
    data.forEach((item) => {
      item['pid'] = 0
      if (item.children) {
        item.children.forEach((target) => {
          target['id'] = item.id + '-' + target.id
          target['children'] = []
        })
      }
    })
    treeData.value = data
    toData.value = []
  } else {
    let leftData = cloneDeep(data)
    let rightData = cloneDeep(data)
    let selectData = JSON.parse(formData.userIds as any)
    leftData = leftData.filter((item) => {
      item['pid'] = 0
      if (item.children) {
        item.children = item.children.filter((target) => {
          if (selectData.indexOf(target.id) == -1) {
            target['id'] = item.id + '-' + target.id
            target['children'] = []
            return true
          } else {
            return false
          }
        })
        return item.children.length > 0
      }
    })

    rightData = rightData.filter((item) => {
      item['pid'] = 0
      if (item.children) {
        item.children = item.children.filter((target) => {
          if (selectData.indexOf(target.id) != -1) {
            target['id'] = item.id + '-' + target.id
            target['children'] = []
            return true
          } else {
            return false
          }
        })
      }
      return item.children.length > 0
    })
    treeData.value = leftData
    toData.value = rightData
    setTimeout(() => {
      treeTransferRef.value.checkedRight = true
      treeTransferRef.value.rightAllCheck()
    }, 0)
  }
}
/** 重置表单 */
const resetForm = () => {
  formData.id = ''
  formData.name = ''
  formData.remark = undefined
  formData.userIds = []
  treeVisible.value = false
  formRef.value?.resetFields()
}
</script>
<style lang="scss" scoped></style>
